/*
 * Copyright (c) 2011. c.mueller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package de.altitude.cimuelle.utils;

import de.altitude.cimuelle.Config;
import de.altitude.cimuelle.MessageBundle;
import de.altitude.cimuelle.coop.CoopGame;
import de.altitude.cimuelle.db.DatabaseManager;
import de.altitude.cimuelle.db.DatabasePlayerInfo;
import org.apache.log4j.Logger;

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

/**
 * Class description:
 * <p/>
 * User: cybernaut
 * Date: 07.10.11
 * Time: 22:11
 */
public class StringUtils {
    private static final Logger LOGGER = Logger.getLogger("StringUtils");

    public static String addslashes(String nickname) {
        return nickname.
                replace("\\", "\\\\").
                replace("\"", "\\\"");
    }

    public static void buildRankString(Config config, String port, List<DatabasePlayerInfo> playerRankInfo, StringBuilder sb) {
        buildRankString(config, port, playerRankInfo, sb, null);
    }

    public static void buildRankString(Config config, String port, List<DatabasePlayerInfo> playerRankInfo, StringBuilder sb, String column) {
        for (DatabasePlayerInfo databasePlayerInfo : playerRankInfo) {

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("RANK", String.valueOf(databasePlayerInfo.getRank()));
            map.put("PLAYERNAME", databasePlayerInfo.getName());

            String points = "";
            if (column != null && column.equals(DatabaseManager.COOP_POINTS_COL)) {
                points = String.valueOf(databasePlayerInfo.getCoopPoints());
            } else {
                if (config.isCoopActiveByPort(port)) {
                    points = String.valueOf(databasePlayerInfo.getTurretKills());
                } else {
                    String orderBy = config.getConfigByPort(port, "rankingOrder", "turretKills");
                    if ("goals".equals(orderBy)) {
                        points = String.valueOf(databasePlayerInfo.getGoals());
                    } else if ("deaths".equals(orderBy)) {
                        points = String.valueOf(databasePlayerInfo.getDeaths());
                    } else if ("kills".equals(orderBy)) {
                        points = String.valueOf(databasePlayerInfo.getKills());
                    } else if ("ratio".equals(orderBy)) {
                        points = databasePlayerInfo.getRatio();
                    }
                }

            }
            map.put("POINTS", points);

            sb.append(MessageBundle.getString("wgenericRank1", map));
        }
        if (config.isDebugVerbose()) {
            LOGGER.debug("rank: " + sb.toString());
        }
        if (sb.toString().isEmpty()) {
            sb.append("Unknown Name");
        }
    }

    public static String removeStringAndBracket(String chatString, String remove) {
        String name = chatString.replace(remove, "");
        name = name.substring(0, name.length() - 1);
        return name;
    }

    public static void buildStatsString(DatabasePlayerInfo playerRankInfo, StringBuilder sb) {
        sb.append("Goals: ");
        sb.append(playerRankInfo.getGoals());
        sb.append(" | Kills: ");
        sb.append(playerRankInfo.getKills());
        sb.append(" | Deaths: ");
        sb.append(playerRankInfo.getDeaths());
        sb.append(" | Ratio: ");
        if (playerRankInfo.getDeaths() > 0) {
            DecimalFormat df = new DecimalFormat("#0.00");
            double ratio = (double) playerRankInfo.getKills() / (double) playerRankInfo.getDeaths();
            sb.append(df.format(ratio));
        } else {
            sb.append(0);
        }
    }

    public static String buildCoopRankString(List<CoopGame> coopGameRanks) {
        StringBuilder sb = new StringBuilder();

        sb.append(MessageBundle.getString("genericCoopRank1Head"));
        for (CoopGame game : coopGameRanks) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("RANK", String.valueOf(game.getRank()));
            map.put("DURATION", String.valueOf(game.getDuration()));

            sb.append(MessageBundle.getString("genericCoopRank2Body", map));
        }
        return sb.toString();
    }

    public static String fillTextFormat(String text, int maxLength, String filler) {
        final Font arial = new Font("Arial", 0, 12);
        FontRenderContext fc = new FontRenderContext(null, true, true);

        final double max = arial.getStringBounds(repeat("w", maxLength), fc).getWidth();
        final double textSize = arial.getStringBounds(text, fc).getWidth();

        final double missing = max - textSize;
        if (missing > 0) {
            final double fillerLength = arial.getStringBounds(filler, fc).getWidth();
            final int times = (int) (missing / fillerLength);
            text = repeat(filler, times) + text;
        }
        return text;
    }

    private static String repeat(String toRepeat, int times) {
        String out = "";
        for (int i = 0; i < times; i++) {
            out += toRepeat;
        }
        return out;
    }
}
